;(function (win, lib) {
    var doc = win.document;
    var docEl = doc.documentElement;
    var metaEl = doc.querySelector('meta[name="viewport"]');
    var layoutMeta = doc.querySelector('meta[name="layout"]');
    var dpr = win.devicePixelRatio || 1;
    var layoutWidth = 720; // 默认设计稿宽度为720px;
    var bodyFontSize = 12; // body 默认字号为12px
    var layout = lib.layout || (lib.layout = {});
    
    var ua = win.navigator.userAgent;
    var iOS = /(iPhone|ipod|ipad|ios)/i.test(ua);
    var isAndroid = win.navigator.appVersion.match(/android/ig);
    var isPC = !(iOS || isAndroid);

    var forceDpr = false;
    var tid, scale, content;

    // 读取通过meta指定的设计稿宽度和body默认字号
    if (layoutMeta && (content = (layoutMeta.getAttribute('content') || ''))) {
        content.match(/width=(\d+)/i);
        RegExp.$1 && (layoutWidth = RegExp.$1);

        content.match(/font-size=(\d+)/i);
        RegExp.$1 && (bodyFontSize = RegExp.$1);

        if (content.match(/dpr(?:=(\d+))?/i)) {
            forceDpr = RegExp.$1 || 1;
        }
    }

    // 目前只处理1，2，3倍屏，不处理1.5，2.5，3.5之类的奇葩屏
    if (dpr >= 3) {
        dpr = 3;
    } else if (dpr >= 2) {
        dpr = 2;
    } else if (dpr > 1) {
        dpr = 1;
    }

    // 安全卫士中的webview，viewport scale < 1 时，处理成了放大(zoom)效果
    // 通过url中的参数  mobilesafe=1 进行识别
    if (/&mobilesafe=1/i.test(location.href)) {
        forceDpr = 1;
    }

    // 强制X倍屏
    if (forceDpr) {
        dpr = forceDpr;
    }

    // PC模式dpr强制为1
    if (isPC) {
        dpr = 1;
    }

    scale = 1 / dpr;
    layout.dpr = dpr;

    // 采用document.write， 尽快让meta生效，防止页面加载时跳跃
    if (!metaEl) {
        var mc = ["initial","maximum","minimum", "user-scalable=no"].join('-scale=' + scale + ',');
        var meta = '<meta name="viewport" content="width=device-width,' + mc + '">';
        
        doc.write(meta);
    } else {
        // todo: 处理已有viewport情况
    }

    // 设置html基准字体
    // 基准设计稿下，1rem=100px
    function setupRem(onRender) {
        var docWidth = docEl.getBoundingClientRect().width;
        var rootFontSize = (docWidth / layoutWidth) * 100;
        
        // PC模式下，最大字号为100px
        if (isPC) {
            rootFontSize = Math.min(rootFontSize,  100);
        }

        docEl.style.fontSize = rootFontSize + 'px';
        lib.layout.rootFontSize = rootFontSize;

        // 某些安卓设备（三星或者HTC)，initial-scale<1时， 缩放viewport会失败
        // 这种情况下我们字体需要设置为1倍屏
        // 检测机制：
        // 如果viewport缩放成功，则docWidth至少是320*2
        if ( isAndroid
            && window.devicePixelRatio > 1 
            && docWidth < 400
        ) {
            layout.dpr = 1;
        }

        if (isPC && docWidth > 540) {
            layout.dpr = 2;
        }

        docEl.setAttribute('data-dpr', layout.dpr);

        // 页面初始化时，设定body字号和常用字号
        if (onRender) {
            var bfs = bodyFontSize * layout.dpr;
            var maxPageRem = layoutWidth / 100;
            var bodyDefaultCSS = 'body {font-size:' + bfs + 'px !important;}';

            if (isPC) {
                var maxPageRem = layoutWidth / 100;

                bodyDefaultCSS += 'body {margin-left:auto !important;margin-right:auto !important;max-width:' + maxPageRem + 'rem;}';
            }

            var defaultCSSList = [];
            for (var i = 10; i <= 40; i++) {
                defaultCSSList.push('.f' + i + '{font-size:' +  layout.dpr * i + 'px !important;}');
            }

            var cssText = [bodyDefaultCSS, defaultCSSList.join("")].join("\n");
            doc.write('<style type="text/css">' + cssText + '</style>');
        }
    }

    win.addEventListener('resize', function () {
        clearTimeout(tid);
        tid = setTimeout(setupRem, 300);
    }, false);

    win.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            clearTimeout(tid);
            tid = setTimeout(setupRem, 300);
        }
    }, false);

    setupRem(true);

    lib.layout.px2rem = function (px) {
        return px / this.rootFontSize;
    };

    lib.layout.rem2px = function (rem) {
        return rem * this.rootFontSize;
    };

    // 计算字号
    lib.layout.fontSize = function(px) {
        return px * this.dpr;
    };

    lib.layout.setupRem = setupRem;

})(window, window['lib'] || (window['lib'] = {}));